/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef IMAGE_KNIFE_C_FILE_CACHE_INTERCEPTOR_OH_H
#define IMAGE_KNIFE_C_FILE_CACHE_INTERCEPTOR_OH_H

#include "interceptor.h"
#include "imageknife_request.h"
#include "file_cache.h"
#include "imageknife_internal.h"
#include "imageknife_data_napi.h"
#include "hitrace/trace.h"

namespace ImageKnifePro {
class FileCacheInterceptorDefault : public FileCacheInterceptor {
public:
    FileCacheInterceptorDefault()
    {
        name = "Default FileCacheInterceptor";
    }

    bool Resolve(std::shared_ptr<ImageKnifeTask> task) override
    {
        bool result = false;
        const int traceId = 1;
        if (task->cacheTask.type == CacheTaskType::WRITE) {
            OH_HiTrace_StartAsyncTrace("FileCacheInterceptor WRITE", traceId);
            result = Write(task);
            OH_HiTrace_FinishAsyncTrace("FileCacheInterceptor WRITE", traceId);
        } else if (task->cacheTask.type == CacheTaskType::READ) {
            OH_HiTrace_StartAsyncTrace("FileCacheInterceptor READ", traceId);
            result = Read(task);
            OH_HiTrace_FinishAsyncTrace("FileCacheInterceptor READ", traceId);
        }

        return result;
    }

private:
    bool Read(std::shared_ptr<ImageKnifeTask> task)
    {
        FileCache::FileData fileData;
        if (FileCache::GetInstance()->GetImageFromDisk(task->cacheTask.cacheKey, fileData)) {
            task->product.imageBuffer = fileData.buffer;
            task->product.imageLength = fileData.size;
            return true;
        }
        return false;
    }

    bool Write(std::shared_ptr<ImageKnifeTask> task)
    {
        if (task->product.imageBuffer == nullptr) {
            task->EchoError("Image Buffer Is Null");
            return false;
        }

        if (!FileCache::GetInstance()->Contains(task->cacheTask.cacheKey)) {
            FileCache::GetInstance()->SaveImageToDisk((char *)(task->product.imageBuffer.get()),
                                                      task->product.imageLength,
                                                      task->cacheTask.cacheKey);
        }
        return true;
    }
};
};

#endif // IMAGE_KNIFE_C_FILE_CACHE_INTERCEPTOR_OH_H
